package com.artifex.mupdf.viewer.app

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.Insets
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class CrashReportActivity : AppCompatActivity() {
    companion object {
        private const val EXTRA_CRASH_REPORT = "extra_crash_report"

        fun start(context: Context, crashReport: String) {
            val intent = Intent(context, CrashReportActivity::class.java).apply {
                putExtra(EXTRA_CRASH_REPORT, crashReport)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ViewCompat.setOnApplyWindowInsetsListener(
            window.decorView,
            OnApplyWindowInsetsListener { v: View?, insets: WindowInsetsCompat? ->
                val systemBars: Insets = insets!!.getInsets(WindowInsetsCompat.Type.systemBars())
                v!!.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
                insets
            })

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_crash_report)

        val crashReport = intent.getStringExtra(EXTRA_CRASH_REPORT) ?: "No crash details available"

        findViewById<TextView>(R.id.crashDetails).text = crashReport
        findViewById<Button>(R.id.restartButton).setOnClickListener {
            restartApp()
        }
    }

    private fun restartApp() {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        intent?.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }
}